/**
 * 商铺绑定弹窗组件
 * 用于在点击3D模型时弹出商铺信息绑定表单
 */

'use client'

import React, { useState, useEffect } from 'react'
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog"
import { createStoreInfo, editStore, getBusinessTypes, getStoreStatusOptions } from '@/lib/api/store'
import { toast } from 'sonner'
import * as THREE from 'three'

interface StoreBindingModalProps {
  isOpen: boolean
  onClose: () => void
  attractionId: string
  floorId?: string
  position?: [number, number]
  meshInfo?: {
    name: string
    object: THREE.Object3D
    point: THREE.Vector3
  }
  editingStore?: {
    id: string
    name: string
    business: string
    description?: string
    contact?: {
      phone?: string
      hours?: string
    }
    status: 'active' | 'inactive' | 'renovation'
  }
  onSuccess?: (storeData: any) => void
}

export const StoreBindingModal: React.FC<StoreBindingModalProps> = ({
  isOpen,
  onClose,
  attractionId,
  floorId,
  position,
  meshInfo,
  editingStore,
  onSuccess
}) => {
  const [formData, setFormData] = useState({
    name: '',
    business: '',
    description: '',
    phone: '',
    hours: '',
    status: 'active' as 'active' | 'inactive' | 'renovation'
  })
  const [isLoading, setIsLoading] = useState(false)

  const businessTypes = getBusinessTypes()
  const statusOptions = getStoreStatusOptions()

  // 初始化表单数据
  useEffect(() => {
    if (editingStore) {
      setFormData({
        name: editingStore.name || '',
        business: editingStore.business || '',
        description: editingStore.description || '',
        phone: editingStore.contact?.phone || '',
        hours: editingStore.contact?.hours || '',
        status: editingStore.status || 'active'
      })
    } else {
      // 重置为空表单
      setFormData({
        name: '',
        business: '',
        description: '',
        phone: '',
        hours: '',
        status: 'active'
      })
    }
  }, [editingStore, isOpen])

  const handleInputChange = (field: string, value: string) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }))
  }

  const handleSubmit = async () => {
    if (!formData.name.trim()) {
      toast.error('请输入商铺名称')
      return
    }

    if (!formData.business) {
      toast.error('请选择业务类型')
      return
    }

    if (!position && !editingStore) {
      toast.error('位置信息缺失')
      return
    }

    setIsLoading(true)

    try {
      const storeData = {
        attractionId,
        floorId,
        name: formData.name,
        business: formData.business,
        position: position!,
        description: formData.description || undefined,
        contact: {
          phone: formData.phone || undefined,
          hours: formData.hours || undefined
        },
        status: formData.status,
        modelInfo: meshInfo ? {
          meshName: meshInfo.name,
          boundingBox: {
            min: [meshInfo.point.x - 1, meshInfo.point.y - 1, meshInfo.point.z - 1] as [number, number, number],
            max: [meshInfo.point.x + 1, meshInfo.point.y + 1, meshInfo.point.z + 1] as [number, number, number]
          }
        } : undefined
      }

      let result
      if (editingStore) {
        // 编辑模式
        result = await editStore(editingStore.id, storeData)
      } else {
        // 新增模式
        result = await createStoreInfo(storeData)
      }

      if (result.success) {
        toast.success(result.msg)
        onSuccess?.(result.data)
        onClose()
      } else {
        toast.error(result.msg)
      }
    } catch (error) {
      console.error('提交商铺信息失败:', error)
      toast.error('提交失败，请重试')
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            🏪 {editingStore ? '编辑商铺信息' : '绑定商铺信息'}
          </DialogTitle>
        </DialogHeader>

        <div className="space-y-4">
          {/* 位置信息显示 */}
          {position && (
            <div className="bg-gray-50 p-3 rounded-lg text-sm">
              <div className="text-gray-600">绑定位置：</div>
              <div className="font-mono text-xs">
                经度: {position[0].toFixed(6)}, 纬度: {position[1].toFixed(6)}
              </div>
              {meshInfo && (
                <div className="text-gray-500 mt-1">
                  模型对象: {meshInfo.name}
                </div>
              )}
            </div>
          )}

          {/* 基本信息 */}
          <div className="space-y-3">
            <div>
              <Label htmlFor="storeName">商铺名称 *</Label>
              <Input
                id="storeName"
                value={formData.name}
                onChange={(e) => handleInputChange('name', e.target.value)}
                placeholder="请输入商铺名称"
              />
            </div>

            <div>
              <Label htmlFor="business">业务类型 *</Label>
              <Select value={formData.business} onValueChange={(value) => handleInputChange('business', value)}>
                <SelectTrigger>
                  <SelectValue placeholder="选择业务类型" />
                </SelectTrigger>
                <SelectContent>
                  {businessTypes.map((type) => (
                    <SelectItem key={type.value} value={type.value}>
                      <span className="flex items-center gap-2">
                        <span>{type.icon}</span>
                        <span>{type.label}</span>
                      </span>
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div>
              <Label htmlFor="status">营业状态</Label>
              <Select value={formData.status} onValueChange={(value: any) => handleInputChange('status', value)}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {statusOptions.map((status) => (
                    <SelectItem key={status.value} value={status.value}>
                      <span className="flex items-center gap-2">
                        <div 
                          className="w-2 h-2 rounded-full" 
                          style={{ backgroundColor: status.color }}
                        />
                        <span>{status.label}</span>
                      </span>
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div>
              <Label htmlFor="description">商铺描述</Label>
              <Textarea
                id="description"
                value={formData.description}
                onChange={(e) => handleInputChange('description', e.target.value)}
                placeholder="请输入商铺描述信息"
                rows={3}
              />
            </div>
          </div>

          {/* 联系信息 */}
          <div className="space-y-3 border-t pt-3">
            <div className="text-sm font-medium text-gray-700">联系信息</div>
            
            <div>
              <Label htmlFor="phone">联系电话</Label>
              <Input
                id="phone"
                value={formData.phone}
                onChange={(e) => handleInputChange('phone', e.target.value)}
                placeholder="请输入联系电话"
              />
            </div>

            <div>
              <Label htmlFor="hours">营业时间</Label>
              <Input
                id="hours"
                value={formData.hours}
                onChange={(e) => handleInputChange('hours', e.target.value)}
                placeholder="例如：09:00-21:00"
              />
            </div>
          </div>
        </div>

        <DialogFooter className="gap-2">
          <Button variant="outline" onClick={onClose} disabled={isLoading}>
            取消
          </Button>
          <Button onClick={handleSubmit} disabled={isLoading}>
            {isLoading ? '保存中...' : (editingStore ? '更新' : '保存')}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}